<template>
  <div>
    <basic-dialog
      :visible="visible"
      min-width="1200px"
      is-show-close
      @close="visible=false"
      isShowBasicFooter
      @submit="submitGateway"
      title="网关选择">
      <q-card-section class="margin-b-10">
        <div>
          <yz-condition-filter
            v-model="queryParams"
            @resetSearch="resetSearch"
            @onSubmit="onSubmit"
            style="margin-top: 4px;"
          >
            <fuzzy-search
              v-model.trim="queryParams.gateWayId"
              isFilter
              title="网关序列号"
              :isShowValue="false"
              :fuzzyObj="['boxNumNoProId', 'boxNum']"
              :fuzzyFunc="fuzzyFunc"
              class="margin-r-20"
            ></fuzzy-search>
            <yz-input v-model="queryParams.connectStatus"
                      inputType="select"
                      :options="connectStatus"
                      title="连接状态"
                      class="margin-r-20"
            ></yz-input>
            <yz-input v-model="queryParams.onLineStatus"
                      inputType="select"
                      :options="gatewayStatusList"
                      title="网关状态"
                      class="margin-r-20"
            ></yz-input>
            <yz-input v-model="queryParams.deploymentStatus"
                      inputType="select"
                      :options="deploymentStatusList"
                      title="部署状态"
                      class="margin-r-20"
            ></yz-input>
            <div class="flex">
              <yz-input v-model="queryParams.deviceType"
                        inputType="select"
                        :options="deviceTypeOptions"
                        title="关联设备(仪表)"
                        class="margin-r-10"
              ></yz-input>
              <fuzzy-search
                v-model.trim="queryParams.deviceId"
                :isShowValue="false"
                showAllOption
                isForm
                smallSize
                title="关联设备或仪表"
                :show-label="false"
                class="margin-r-20"
                style="width: 220px"
                :options="deviceIdOptions"
                filterByFe
              ></fuzzy-search>
            </div>
          </yz-condition-filter>
        </div>
      </q-card-section>
      <q-table
        :data="tableData"
        :columns="columns"
        style="height: 400px"
        row-key="prodId"
        class="myTable scroll"
        :loading="tableLoading"
        :pagination="pagination"
        hide-bottom
        separator="cell"
        no-data-label="暂无数据"
        color="primary"
        selection="multiple"
        :selected.sync="selected"
      >
        <template v-slot:body-cell-onLineStatus="props">
          <q-td :props="props">
            <div class="living">
              <div class="status" :class="{'offline': props.row.onLineStatus !== 'ONLINE'}"></div>
              {{props.row.onLineStatus === 'ONLINE' ? '在线':'离线'}}
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-connectStatus="props">
          <q-td :props="props">
            <div class="living" v-if="connectStatusObj[props.row.connectStatus]">
              <div class="status" :class="props.row.connectStatus"></div>
              {{ connectStatusObj[props.row.connectStatus]}}
            </div>
            <div v-else>--</div>
          </q-td>
        </template>
        <template v-slot:body-cell-deploymentStatus="props">
          <q-td :props="props">
            <div class="living" v-if="deploymentStatusObj[props.row.deploymentStatus]">
              <div class="status" :class="getDeployStatus(props.row.deploymentStatus)"></div>
              {{ deploymentStatusObj[props.row.deploymentStatus]}}
            </div>
            <div v-else>--</div>
          </q-td>
        </template>
        <template v-slot:body-cell-deviceCount="props">
          <q-td :props="props">
            <div class="device-count" @click="toDeviceDetail(props.row)">{{props.row.deviceCount}}</div>
          </q-td>
        </template>
      </q-table>
      <div  style="width: 100%;" :style="{'height': noPagination ? '20px' : ''}">
        <pagination
          style="position: relative;padding: 20px"
          v-if="tableData.length > 0 && !noPagination"
          v-model="pagination.page"
          :page-size="pagination.rowsPerPage"
          :total="pagination.rowsNumber"
          @changePage="onPageChange"
          @changePageSize="onPageSizeChange"
        >
        </pagination>
      </div>
    </basic-dialog>
    <!-- 设备详情 -->
    <DeviceInfos ref="deviceInfos" />
  </div>
</template>

<script>
import {
  deploymentStatusObj,
  connectStatusObj,
  connectStatus,
  gatewayStatusList, deviceTypeOptions, deploymentStatusList
} from '../../../components/list-components/plc-dialog/constant'
import { boxMatchQuery, boxQueryList, deviceNumWithBox } from '../../../../../boot/miot/list'
import { energyUseBoxNum } from '../../../../../boot/miot/plc-list'
import Pagination from 'src/components/pagination'
import DeviceInfos from '../../../components/list-components/device-infos.vue'
import { controllerTypeObj } from '../../../components/list-components/gateway-dialog/constant'

export default {
  name: 'add-gateway',
  components: {
    DeviceInfos,
    Pagination
  },
  props: {
    selectedData: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      fuzzyFunc: boxMatchQuery,
      deploymentStatusObj: deploymentStatusObj,
      connectStatusObj: connectStatusObj,
      connectStatus: connectStatus,
      gatewayStatusList: gatewayStatusList,
      deploymentStatusList: deploymentStatusList,
      deviceTypeOptions: deviceTypeOptions,
      visible: false,
      tableLoading: false,
      // 表格分页配置
      pagination: {
        // 页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      columns: [
        { name: 'prodId', label: '网关序列号', align: 'left', field: 'prodId' },
        { name: 'onLineStatus', label: '网关状态(IOTDA)', align: 'left', field: 'onLineStatus' },
        { name: 'connectStatus', label: '连接状态(Ucloud)', align: 'left', field: 'connectStatus' },
        { name: 'deploymentStatus', label: '部署状态(Ucloud)', align: 'left', field: 'deploymentStatus' },
        { name: 'deviceCount', label: '关联设备', align: 'left', field: 'deviceCount' }
      ],
      tableData: [],
      queryParams: {
        deviceId: null,
        gateWayId: null,
        connectStatus: null,
        deploymentStatus: null,
        onLineStatus: null,
        deviceType: '1',
        driver: null,
        updateVersion: null
      },
      selected: [],
      deviceIdOptions: [],
      params: {}
    }
  },
  watch: {
    'queryParams.deviceType': {
      immediate: true,
      handler: function (val) {
        this.queryParams.deviceId = ''
        this.deviceIdOptions = []
        if (val === '1') {
          this.getDeviceNumWithBox()
        } else if (val === '2') {
          this.getEnergyUseBoxNum()
        }
      }
    },
    selectedData: {
      deep: true,
      immediate: true,
      handler (val) {
        this.selected = val
      }
    }
  },
  computed: {
    noPagination () {
      return !!this.params.deploymentStatus ||
        !!this.params.onLineStatus ||
        !!this.params.connectStatus ||
        !!this.params.startDate
    }
  },
  methods: {
    showDialog (taskType, driver) {
      this.visible = true
      this.resetSearch()
      // 如果是升级驱动
      if (taskType === '4') {
        this.queryParams.driver = driver
        this.queryParams.updateVersion = 2
      } else {
        this.queryParams.updateVersion = null
      }
      this.searchList(this.queryParams)
    },
    // 查询
    async searchList (queryParams) {
      if (queryParams) {
        this.queryParams = queryParams
        this.params.boxId = queryParams.gateWayId
        this.params.deploymentStatus = queryParams.deploymentStatus
        this.params.onLineStatus = queryParams.onLineStatus
        this.params.deviceId = queryParams.deviceId
        this.params.deviceType = queryParams.deviceType
        this.params.connectStatus = queryParams.connectStatus
        this.params.driverName = queryParams.driver
        this.params.updateVersion = queryParams.updateVersion
      }
      // 如果不需要分页的话
      if (this.noPagination) {
        this.params.pageNum = null
        this.params.pageSize = null
      } else {
        this.params.pageNum = this.pagination.page
        this.params.pageSize = this.pagination.rowsPerPage
      }
      // 只查询新架构的
      this.params.isNewBoxArch = 1
      this.loading = true
      try {
        this.tableLoading = true
        const { data } = await boxQueryList(this.params)
        if (data && data.list && data.list.length > 0) {
          data.list.forEach(item => {
            item.deviceCount = item.deviceInfo?.length || 0
            item.prodId = this.getProdId(item.boxId)
          })
          this.tableData = data.list
          this.pagination.rowsNumber = data.total
        } else {
          this.tableData = []
        }
      } catch (e) {
      } finally {
        this.tableLoading = false
      }
    },
    // 获取显示的prodid
    getProdId (boxId) {
      if (!boxId) return '--'
      try {
        const data = boxId.split('_')
        if (data.length === 1) return data[0]
        if (data.length === 2) return data[1]
      } catch (e) {
        return '--'
      }
    },
    onSubmit () {
      this.pagination.page = 1
      this.searchList(this.queryParams)
    },
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      Object.assign(this.params, this.$options.data.call(this).params)
    },
    // 获取部署状态的class
    getDeployStatus (status) {
      const obj = {
        'success': 'online',
        'failed': 'failed',
        'processing': 'inactivated',
        'undeploy': 'offline',
        'timeout': 'failed'
      }
      return obj[status]
    },
    // 获取设备
    getDeviceNumWithBox () {
      deviceNumWithBox().then(res => {
        if (res && res.data && res.data.length > 0) {
          this.deviceIdOptions = res.data.map(item => {
            return {
              label: `${item.deviceName}(${item.assetNumber})`,
              value: item.id
            }
          })
        } else {
          this.deviceIdOptions = []
        }
      })
    },

    // 获取能耗设备
    getEnergyUseBoxNum () {
      energyUseBoxNum().then(res => {
        if (res && res.data && res.data.length > 0) {
          this.deviceIdOptions = res.data.map(item => {
            return {
              label: `${item.instruName}(${item.instruCode})`,
              value: item.instruId
            }
          })
        } else {
          this.deviceIdOptions = []
        }
      })
    },

    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.searchList(this.queryParams)
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.searchList(this.queryParams)
    },
    // 提交
    submitGateway () {
      this.visible = false
      this.$emit('submit', this.selected)
    },
    // 跳转到设备详情
    toDeviceDetail (row) {
      const deviceInfo = row.deviceInfo || []
      const result = deviceInfo.map((item, index) => {
        return {
          index: index + 1,
          controllerType: controllerTypeObj[item.isPlc],
          driver: item.driverName,
          deviceName: '',
          deviceNum: item.assetNum,
          device: `${item.deviceName}(${item.assetNum})`
        }
      })
      this.$refs.deviceInfos.showDialog(result)
    }
  }
}
</script>
<style scoped lang="scss">
.status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: $positive;
}
.online {
  background: $positive;
}
.inactivated {
  background: $warning;
}
.offline {
  background: #666666;
}
.failed {
  background: $negative;
}
.device-count{
  color: #5f77fd;
  cursor: pointer;
}
</style>
